package xcmg.device.service.threeGuaranteesPur;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.DataDictionaryDO;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesOutDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesOutDetailDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesPurDO;
import xcmg.device.dao.entity.threeGuaranteesPur.ThreeGuaranteesPurDetailDO;
import xcmg.device.dao.entity.warehouse.WarehouseInventoryDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.DataDictionaryMapper;
import xcmg.device.dao.mapper.MaterialLocationRelationMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.threeGuaranteesPur.ThreeGuaranteesOutDetailMapper;
import xcmg.device.dao.mapper.threeGuaranteesPur.ThreeGuaranteesPurDetailMapper;
import xcmg.device.dao.mapper.threeGuaranteesPur.ThreeGuaranteesPurMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDeliveryDetailMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInventoryMapper;
import xcmg.device.infra.DateUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExcelUtil;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.infra.enums.BillDesc;
import xcmg.device.infra.enums.GuaraenteesStatus;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.basic.MaterialsService;
import xcmg.device.service.company.CompanyDealerService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.vo.ExternalParamCheckVO;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.MaterialLocationRelationVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurAddVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurAllDetailVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurDetailQueryVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurDetailVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurExportVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurJCAddHeadInfo;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurJCAddVO;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurJCDetail;
import xcmg.device.service.vo.threeGuaranteesPur.ThreeGuaranteesPurVO;
import xcmg.device.service.vo.warehouse.WarehouseInventoryVO;
import xcmg.device.service.vo.warehouse.app.EnableAndOccupyVO;
import xcmg.device.service.warehouse.WarehouseInventoryService;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.dto.UserCacheDTO;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ThreeGuaranteesPurService {
    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private ThreeGuaranteesPurMapper threeGuaranteesPurMapper;

    @Autowired
    private ThreeGuaranteesPurDetailMapper threeGuaranteesPurDetailMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private DataDictionaryMapper dataDictionaryMapper;

    @Autowired
    private AuthClient authClient;

    @Autowired
    private MaterialsService materialsService;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private CompanyDealerMapper companyDealerMapper;
    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;

    @Autowired
    private MaterialLocationRelationMapper materialLocationRelationMapper;

    @Autowired
    private ThreeGuaranteesOutDetailMapper threeGuaranteesOutDetailMapper;

    @Autowired
    private WarehouseInventoryService warehouseInventoryService;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private WarehouseDeliveryDetailMapper warehouseDeliveryDetailMapper;

    @Autowired
    private CompanyDealerService companyDealerService;

    @Autowired
    private ExternalParamCheckService externalParamCheckService;
    @Autowired
    private ThreeGuaranteesOutService threeGuaranteesOutService;


    @Value("${spring.file.download.path}")
    private String filePath;
    private  String templateExcelFileName="ThreeGuaPur.xls";

    private  static void rounding(ThreeGuaranteesPurDO entity){

        if(entity.getPrice()!=null){
            //取整
            entity.setPrice(entity.getPrice().multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP));
        }
        if(entity.getTotalPrice()!=null){
            //取整
            entity.setTotalPrice(entity.getTotalPrice().multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP));
        }

    }

    private  static void takeDecimals(ThreeGuaranteesPurVO model){

        if(model.getPrice()!=null){
            model.setPrice(model.getPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
        }
        if(model.getTotalPrice()!=null){
            model.setTotalPrice(model.getTotalPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
        }

    }

    private static BigDecimal takeDecimals(BigDecimal integer){
        if(integer==null){
            return new BigDecimal(0);
        }
        return integer.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);
    }

    private static BigDecimal rounding(BigDecimal decimal){
        if(decimal==null){
            return new BigDecimal(0);
        }
        return decimal.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP);
    }



    @Transactional(rollbackFor = Exception.class)
    public synchronized ErrorCode addLvdaidiao(ThreeGuaranteesPurAddVO threeGuaranteesPurAddVO, String orgId)throws Exception{
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        ThreeGuaranteesPurVO headerInfo = threeGuaranteesPurAddVO.getHeaderInfo();
        BeanUtils.copyProperties(headerInfo,threeGuaranteesPurDO);
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        threeGuaranteesPurDO.setId(text.getValue().toString());
        threeGuaranteesPurAddVO.getHeaderInfo().setId(threeGuaranteesPurDO.getId());
        threeGuaranteesPurDO.setPurchaseNo(genDocumentService.genDocumentNo(BillDesc.Purchase, orgId));
        rounding(threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setTotalPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setOrgId(orgId);
        threeGuaranteesPurDO.setStatus(0);
        threeGuaranteesPurDO.setCrmOrder(headerInfo.getInstructionCode());
        threeGuaranteesPurDO.setMachineNumber(headerInfo.getCarNo());
        threeGuaranteesPurDO.setServiceSite(headerInfo.getSite());
        threeGuaranteesPurDO.setGuaranteesTypeName(headerInfo.getGuaranteesTypeName());
        threeGuaranteesPurDO.setServicePhone(headerInfo.getApplicationPhone());
        threeGuaranteesPurDO.setNote(headerInfo.getNote());
        threeGuaranteesPurDO.setServiceName(headerInfo.getApplicationName());
        if(!StringUtil.isNullOrEmpty(threeGuaranteesPurDO.getSapTypeName())){
            threeGuaranteesPurDO.setSapTypeName(threeGuaranteesPurDO.getSapTypeName().toUpperCase());
        }
        DataDictionaryDO auditDataDictionaryDO=dataDictionaryMapper.itemByCode( GuaraenteesStatus.Name.toString(),threeGuaranteesPurDO.getGuaraenteesStatus());
        if(auditDataDictionaryDO!=null){
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        BigDecimal purQty = BigDecimal.ZERO;
        for(ThreeGuaranteesPurDetailVO detailVO:threeGuaranteesPurAddVO.getDetailList()){
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO,threeGuaranteesPurDetailDO);
            ActionResult<String> textScheduleDetail=fastGenClient.textGuid();
            if(textScheduleDetail.getCode()!=ErrorCode.Success.getCode()){
                return ErrorCode.IllegalArument;
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue().toString());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            threeGuaranteesPurDetailDO.setDeliveryQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setStatus(0);
            threeGuaranteesPurDetailDO.setRealQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            threeGuaranteesPurDetailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            threeGuaranteesPurDetailDO.setPrice(rounding(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        threeGuaranteesPurMapper.add(threeGuaranteesPurDO);
        return ErrorCode.Success;
    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized ErrorCode add(ThreeGuaranteesPurAddVO threeGuaranteesPurAddVO, String orgId)throws Exception{
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        BeanUtils.copyProperties(threeGuaranteesPurAddVO.getHeaderInfo(),threeGuaranteesPurDO);
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return ErrorCode.IllegalArument;
        }
        threeGuaranteesPurDO.setId(text.getValue().toString());
        threeGuaranteesPurAddVO.getHeaderInfo().setId(threeGuaranteesPurDO.getId());
        threeGuaranteesPurDO.setPurchaseNo(genDocumentService.genDocumentNo(BillDesc.Purchase, orgId));
        rounding(threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setTotalPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setOrgId(orgId);
        threeGuaranteesPurDO.setStatus(0);
        if(!StringUtil.isNullOrEmpty(threeGuaranteesPurDO.getSapTypeName())){
            threeGuaranteesPurDO.setSapTypeName(threeGuaranteesPurDO.getSapTypeName().toUpperCase());
        }
        DataDictionaryDO auditDataDictionaryDO=dataDictionaryMapper.itemByCode( GuaraenteesStatus.Name.toString(),threeGuaranteesPurDO.getGuaraenteesStatus());
        if(auditDataDictionaryDO!=null){
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        BigDecimal purQty = BigDecimal.ZERO;
        for(ThreeGuaranteesPurDetailVO detailVO:threeGuaranteesPurAddVO.getDetailList()){
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO,threeGuaranteesPurDetailDO);
            ActionResult<String> textScheduleDetail=fastGenClient.textGuid();
            if(textScheduleDetail.getCode()!=ErrorCode.Success.getCode()){
                return ErrorCode.IllegalArument;
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue().toString());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            threeGuaranteesPurDetailDO.setDeliveryQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setStatus(0);
            threeGuaranteesPurDetailDO.setRealQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            threeGuaranteesPurDetailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            threeGuaranteesPurDetailDO.setPrice(rounding(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        threeGuaranteesPurMapper.add(threeGuaranteesPurDO);
        return ErrorCode.Success;
    }

    public ErrorCode remove(List<String> ids, String orgId){
        List<String> billNos = threeGuaranteesPurMapper.findBillNos(ids);
        if(threeGuaranteesPurMapper.findForDeleteByIds(billNos, orgId) > 0){
            return ErrorCode.ThreePurchaseDeleteError;
        }
        threeGuaranteesPurMapper.remove(ids);
        threeGuaranteesPurDetailMapper.removeByPurIdList(ids);
        return ErrorCode.Success;
    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized ErrorCode update(ThreeGuaranteesPurAddVO threeGuaranteesPurAddVO){
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        takeDecimals(threeGuaranteesPurAddVO.getHeaderInfo());
        BeanUtils.copyProperties(threeGuaranteesPurAddVO.getHeaderInfo(),threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setTotalPrice(new BigDecimal(0));
        if(!StringUtil.isNullOrEmpty(threeGuaranteesPurDO.getSapTypeName())){
            threeGuaranteesPurDO.setSapTypeName(threeGuaranteesPurDO.getSapTypeName().toUpperCase());
        }
        DataDictionaryDO auditDataDictionaryDO=dataDictionaryMapper.itemByCode( GuaraenteesStatus.Name.toString(),threeGuaranteesPurDO.getGuaraenteesStatus());
        if(auditDataDictionaryDO!=null){
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        threeGuaranteesPurDetailMapper.deleteBy(threeGuaranteesPurAddVO.getHeaderInfo().getId());
        BigDecimal purQty = BigDecimal.ZERO;
        for(ThreeGuaranteesPurDetailVO detailVO:threeGuaranteesPurAddVO.getDetailList()){
            ActionResult<String> textDetailVO=fastGenClient.textGuid();
            if(textDetailVO.getCode()!=ErrorCode.Success.getCode()){
                return ErrorCode.IllegalArument;
            }
            ThreeGuaranteesPurDetailDO detailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO,detailDO);
            detailDO.setId(textDetailVO.getValue().toString());
            detailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            detailDO.setDeliveryQty(BigDecimal.ZERO);
            detailDO.setStatus(0);
            detailDO.setRealQty(BigDecimal.ZERO);
            detailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            detailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            detailDO.setPrice(rounding(detailDO.getPrice()));
            detailDO.setTotalPrice(detailDO.getPrice().multiply(detailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(detailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(detailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(detailDO.getTotalPrice()));
            purQty = purQty.add(detailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        threeGuaranteesPurMapper.update(threeGuaranteesPurDO);
        return ErrorCode.Success;
    }

    @Transactional(rollbackFor = Exception.class)
    public  ErrorCode adjust(ThreeGuaranteesPurAddVO threeGuaranteesPurAddVO) throws Exception {
        //校验创建出库单数量与修改数量比较
        List<ThreeGuaranteesPurDetailVO> detailList = threeGuaranteesPurAddVO.getDetailList();
        if (null == detailList || detailList.isEmpty()){
            return ErrorCode.IllegalArument;
        }
        for (ThreeGuaranteesPurDetailVO threeGuaranteesPurDetailVO: detailList) {
            BigDecimal amount = threeGuaranteesPurDetailVO.getPurchaseQty();
            BigDecimal deliveryQty = threeGuaranteesPurDetailVO.getDeliveryQty();
            if (null == deliveryQty || deliveryQty.compareTo(BigDecimal.ZERO)==0){
                continue;
            }
            if (amount.compareTo(deliveryQty) < 0){
                return ErrorCode.AdjustMountNotOutError;
            }
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        String mainId = threeGuaranteesPurAddVO.getHeaderInfo().getId();
        String applicationId = threeGuaranteesPurAddVO.getHeaderInfo().getApplicationId();
        String applicationName = threeGuaranteesPurAddVO.getHeaderInfo().getApplicationName();
        threeGuaranteesPurDO.setId(mainId);
        threeGuaranteesPurDO.setReceiverAddress(threeGuaranteesPurAddVO.getHeaderInfo().getReceiverAddress());
        threeGuaranteesPurDO.setReceiverName(threeGuaranteesPurAddVO.getHeaderInfo().getReceiverName());
        threeGuaranteesPurDO.setReceiverPhone(threeGuaranteesPurAddVO.getHeaderInfo().getReceiverPhone());
        threeGuaranteesPurDO.setReceiverFax(threeGuaranteesPurAddVO.getHeaderInfo().getReceiverFax());
        List<ThreeGuaranteesPurDetailDO> guaranteesPurDetailList = threeGuaranteesPurDetailMapper.list(mainId);
        BigDecimal purQty = BigDecimal.ZERO;
        threeGuaranteesPurDO.setPrice(new BigDecimal(0));
        threeGuaranteesPurDO.setTotalPrice(new BigDecimal(0));
        for(ThreeGuaranteesPurDetailVO detailVO:threeGuaranteesPurAddVO.getDetailList()){
            ThreeGuaranteesPurDetailDO detailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO,detailDO);
            guaranteesPurDetailList.removeIf(s -> StringUtils.isNotBlank(detailDO.getId()) && s.getId().equals(detailDO.getId()));

            String detailId = detailDO.getId();
            if (StringUtils.isBlank(detailId)){
                ActionResult<String> textDetailVO=fastGenClient.textGuid();
                if(textDetailVO.getCode()!=ErrorCode.Success.getCode()){
                    return ErrorCode.IllegalArument;
                }
                detailDO.setId(textDetailVO.getValue());
                detailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
                detailDO.setDeliveryQty(BigDecimal.ZERO);
                detailDO.setStatus(0);
                detailDO.setRealQty(BigDecimal.ZERO);
                detailDO.setCreateId(applicationId);
                detailDO.setCreateName(applicationName);
                detailDO.setPrice(rounding(detailDO.getPrice()));
                detailDO.setTotalPrice(detailDO.getPrice().multiply(detailDO.getPurchaseQty()));
                threeGuaranteesPurDetailMapper.add(detailDO);
                threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(detailDO.getPrice()));
                threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(detailDO.getTotalPrice()));
                purQty = purQty.add(detailDO.getPurchaseQty());
            }else{
                detailDO.setPrice(rounding(detailDO.getPrice()));
                detailDO.setTotalPrice(detailDO.getPrice().multiply(detailDO.getPurchaseQty()));
                threeGuaranteesPurDetailMapper.update(detailDO);
                threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(detailDO.getPrice()));
                threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(detailDO.getTotalPrice()));
                purQty = purQty.add(detailDO.getPurchaseQty());
            }
        }

        if(!CollectionUtils.isEmpty(guaranteesPurDetailList)){
            for(ThreeGuaranteesPurDetailDO sidDO:guaranteesPurDetailList){
                if(sidDO.getDeliveryQty().compareTo(new BigDecimal(0))!=0){
                    return ErrorCode.AdjustCannotThreeOutDelete;
                }
                if(threeGuaranteesPurDetailMapper.delete(sidDO.getId())<=0){
                    return ErrorCode.AdjustDeleteError;
                }
            }
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        threeGuaranteesPurMapper.update(threeGuaranteesPurDO);
        return ErrorCode.Success;
    }

    public ErrorCode auditBill(ThreeGuaranteesPurVO threeGuaranteesPurVO) throws Exception{
        if(threeGuaranteesPurVO.getId()==null||threeGuaranteesPurVO.getId()==""){
            return ErrorCode.ThreePurchaseNo;
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO=threeGuaranteesPurMapper.item(threeGuaranteesPurVO.getId());
        if(threeGuaranteesPurDO==null){
            return ErrorCode.ThreePurchaseId;
        }
        if(!threeGuaranteesPurDO.getGuaraenteesStatus().equals(GuaraenteesStatus.WaitAudit.toString())){
            return ErrorCode.ThreePurchaseNotAudit;
        }
        DataDictionaryDO auditDataDictionaryDO=dataDictionaryMapper.itemByCode( GuaraenteesStatus.Name.toString(),threeGuaranteesPurVO.getGuaraenteesStatus());
        if(auditDataDictionaryDO!=null){
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        threeGuaranteesPurDO.setGuaraenteesStatus(threeGuaranteesPurVO.getGuaraenteesStatus());
        threeGuaranteesPurDO.setRealAuditDate(new Date());
        threeGuaranteesPurDO.setRealAuditId(threeGuaranteesPurVO.getRealAuditId());
        threeGuaranteesPurDO.setAuditNote(threeGuaranteesPurVO.getAuditNote());
        ActionResult userAuth =  authClient.getUserDetail(threeGuaranteesPurDO.getRealAuditId());
        UserCacheDTO userInfo = (UserCacheDTO) userAuth.getValue();
        if(userInfo!=null){
            threeGuaranteesPurDO.setRealAuditName(userInfo.getName());
        }
        return threeGuaranteesPurMapper.update(threeGuaranteesPurDO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    public PageCommonVO list(SearchCommonVO<ThreeGuaranteesPurVO> condition){
        PageCommonVO result = new PageCommonVO();
        condition.getFilters().setBillNosList(xcmg.device.infra.StringUtil.getStrSplitList(condition.getFilters().getBillNos()));
        if (!StringUtils.isEmpty(condition.getFilters().getPurchaseNames())) {
            List<String> purchaseNamesList = companyDealerService.listFullNamesByShortName(condition.getFilters().getOrgId(), condition.getFilters().getPurchaseNames());
            if (CollectionUtils.isEmpty(purchaseNamesList)) {
                result.setPageInfo(new PageInfo(new ArrayList()));
                result.setPageInfoList(new ArrayList<>());
                return result;
            }
            condition.getFilters().setPurchaseNamesList(purchaseNamesList);
        }
        PageHelperPlus.orderBy("application_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ThreeGuaranteesPurDO> doList = threeGuaranteesPurMapper.list(condition.getFilters());
        List<ThreeGuaranteesPurVO> voList = new ArrayList<>();
        for (ThreeGuaranteesPurDO entity : doList) {
            ThreeGuaranteesPurVO model = new ThreeGuaranteesPurVO();
            BeanUtils.copyProperties(entity, model);
            takeDecimals(model);
            Integer status = model.getStatus();
            //出库状态下才返回出库时间
            if (status == null || status.compareTo(2) != 0) {
                entity.setOutDate(null);
            }
            List<String> outBillNos = threeGuaranteesOutService.getOutBillNos(entity.getPurchaseNo());
            model.setOutBillNos(outBillNos);
            voList.add(model);
        }
        result.setPageInfo(new PageInfo(doList));
        result.setPageInfoList(voList);
        return result;
    }

    public ThreeGuaranteesPurAddVO item(String threeGuaPurNo,String warehouseCode){
        ThreeGuaranteesPurAddVO result = new ThreeGuaranteesPurAddVO();
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurMapper.item(threeGuaPurNo);
        ThreeGuaranteesPurVO threeGuaranteesPurVO = new ThreeGuaranteesPurVO();
        BeanUtils.copyProperties(threeGuaranteesPurDO,threeGuaranteesPurVO);
        if(threeGuaranteesPurDO == null){
            return result;
        }
        CompanyInfoDO companyInfoDO= companyInfoMapper.item(threeGuaranteesPurDO.getOrgId());
        if(companyInfoDO!=null){
            threeGuaranteesPurVO.setSupplierOrgName(companyInfoDO.getCompanyName());
        }
        result.setHeaderInfo(threeGuaranteesPurVO);
        List<ThreeGuaranteesPurDetailVO> listVO = new ArrayList<>();
        List<ThreeGuaranteesPurDetailDO> listDO = threeGuaranteesPurDetailMapper.list(threeGuaPurNo);
        WarehouseInventoryVO request=new WarehouseInventoryVO();
        request.setOrgId(threeGuaranteesPurDO.getOrgId());
        EnableAndOccupyVO enableAndOccupyVO;
        for(ThreeGuaranteesPurDetailDO entity:listDO){
            ThreeGuaranteesPurDetailVO model = new ThreeGuaranteesPurDetailVO();
            BeanUtils.copyProperties(entity,model);
            model.setPrice(takeDecimals(model.getPrice()));
            model.setTotalPrice(takeDecimals(model.getTotalPrice()));
            MaterialLocationRelationVO materialLocation=new MaterialLocationRelationVO();
            materialLocation.setOrgId(threeGuaranteesPurDO.getOrgId());
            materialLocation.setMaterialNo(entity.getMaterialsNo());
            MaterialsVO mv=priMaterialsMapper.selectMinimumBuy(threeGuaranteesPurDO.getOrgId(),entity.getMaterialsNo());
            if(mv!=null){
                model.setIsMinimumBuy(mv.getIsMinimumBuy());
                model.setMinimumBuy(mv.getMinimumBuy());
            }
            List<MaterialLocationRelationVO> mlr=materialLocationRelationMapper.list(materialLocation);
            model.setStockLocationList(mlr);
            enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(entity.getMaterialsNo(), threeGuaranteesPurDO.getOrgId(), warehouseCode);
            BeanUtils.copyProperties(enableAndOccupyVO, model);
            model.setAmount(model.getEnableNum());
            listVO.add(model);
        }
     result.setDetailList(listVO);
        return result;
    }

    public List<ThreeGuaranteesPurDetailVO> findDeliveryNum(String id, String warehouseCode, String orgId) {
        List<ThreeGuaranteesPurDetailVO> listVO = new ArrayList<>();
        List<ThreeGuaranteesPurDetailDO> listDO = threeGuaranteesPurDetailMapper.list(id);
        if (ListUtil.isNullOrEmpty(listDO)) {
            return null;
        }
        for (ThreeGuaranteesPurDetailDO purDetailDO : listDO) {
            ThreeGuaranteesPurDetailVO purDetailVO = new ThreeGuaranteesPurDetailVO();
            purDetailVO.setMaterialsNo(purDetailDO.getMaterialsNo());
            purDetailVO.setDeliveryNum(warehouseDeliveryDetailMapper.findOccupyNum(purDetailDO.getMaterialsNo(), orgId, warehouseCode));
            purDetailVO.setEnableNum(warehouseInventoryMapper.findEnableNum(purDetailDO.getMaterialsNo(), orgId, warehouseCode));
            listVO.add(purDetailVO);
        }
        return listVO;
    }

    //导出
    public void export(List<String> threeGuaranteesIds,String warehouseCode) throws Exception{
        List<ThreeGuaranteesPurDO> threeGuaranteesPurDOList=threeGuaranteesPurMapper.findByIds(threeGuaranteesIds);
        List<ThreeGuaranteesPurAddVO> threeGuaranteesPurAddVO=new ArrayList<>();
        for(ThreeGuaranteesPurDO ThreeGuaranteesPurDO:threeGuaranteesPurDOList){
            threeGuaranteesPurAddVO.add(this.item(ThreeGuaranteesPurDO.getId(),warehouseCode));
        }
        invokeExport(threeGuaranteesPurAddVO);
    }

    public void exportV2(List<String> threeGuaranteesIds,String warehouseCode) throws Exception {
        if(CollectionUtils.isEmpty(threeGuaranteesIds)){
            invokeExportV2(new ArrayList<>());
        }
        List<ThreeGuaranteesPurExportVO> threeGuaranteesPurs=threeGuaranteesPurMapper.exportByIds(threeGuaranteesIds,warehouseCode);
        invokeExportV2(threeGuaranteesPurs);

    }

    public void exportAllV2(ThreeGuaranteesPurVO condition)throws Exception{
        condition.setBillNosList(xcmg.device.infra.StringUtil.splitList(condition.getBillNos()));
        String purchaseNames = condition.getPurchaseNames();
        if(!StringUtils.isEmpty(purchaseNames)){
            List<String> purchaseNamesList = companyDealerService.listFullNamesByShortName(condition.getOrgId(), purchaseNames);
            if (CollectionUtils.isEmpty(purchaseNamesList)) {
                // 导出空数据
                invokeExportV2(new ArrayList<ThreeGuaranteesPurExportVO>());
            }
            condition.setPurchaseNamesList(purchaseNamesList);
        }
        //获取导出数据
        List<ThreeGuaranteesPurExportVO> threeGuaranteesPurExports = threeGuaranteesPurMapper.exportData(condition);
        invokeExportV2(threeGuaranteesPurExports);
    }

    /**
     * @Des 三包申请报表导出
     * @Date 2020/11/9 15:11
     * @Author wangzhaoyu
     * @Param [objects]
     * @Return void
     */
    private void invokeExportV2(List<ThreeGuaranteesPurExportVO> datas) throws Exception {
        String title = "三包申请导出";
        String[] rowsName = new String[]{"序号", "申请单号", "客户名称", "采购金额", "发货方式", "调度员",
                "审核人", "审核时间","申请人", "申请时间", "状态", "审核意见", "备注", "零件编码", "零件名称", "单位",
                "参考单价(￥)", "申请数量", "可用库存", "合计(￥)", "服务信息单号", "是否返厂","实际返厂", "发运时间", "序列号" ,
                "已建出库数量", "实际出库数量","出库状态","收货地址","出库时间","车型","车号","CRM单据号（备件指令单号）","服务人员","服务网点","明细出库状态","签收时间"};
        Object[] objs = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Object[]> dataList = new ArrayList<Object[]>();
        for(int i = 0 ; i< datas.size();i++){
            ThreeGuaranteesPurExportVO threeGuaranteesPurExportData = datas.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = threeGuaranteesPurExportData.getPurchaseNo();
            objs[2] = threeGuaranteesPurExportData.getCustomerName();
            objs[3] = takeDecimals(threeGuaranteesPurExportData.getTotalPrice());
            objs[4] = threeGuaranteesPurExportData.getDeliveryTypeName();
            objs[5] = threeGuaranteesPurExportData.getDispatcherName();
            objs[6] = threeGuaranteesPurExportData.getRealAuditName() == null ? "" : threeGuaranteesPurExportData.getRealAuditName();
            objs[7] = threeGuaranteesPurExportData.getRealAuditDate() == null ? "" : DateUtil.formatDateTime(threeGuaranteesPurExportData.getRealAuditDate());
            objs[8] = threeGuaranteesPurExportData.getApplicationName();
            objs[9] = DateUtil.formatDateTime(threeGuaranteesPurExportData.getApplicationDate());
            objs[10] = threeGuaranteesPurExportData.getStatusDesc();
            objs[11] = threeGuaranteesPurExportData.getAuditNote();
            objs[12] = threeGuaranteesPurExportData.getNote();
            objs[13] = threeGuaranteesPurExportData.getMaterialsNo();
            objs[14] = threeGuaranteesPurExportData.getMaterialsDesc() == null ? "" : threeGuaranteesPurExportData.getMaterialsDesc();
            objs[15] = threeGuaranteesPurExportData.getUnit() == null ? "" : threeGuaranteesPurExportData.getUnit();
            objs[16] = takeDecimals(threeGuaranteesPurExportData.getPrice());
            objs[17] = threeGuaranteesPurExportData.getPurchaseQty() == null ? "" : threeGuaranteesPurExportData.getPurchaseQty();
            objs[18] = threeGuaranteesPurExportData.getEnableNum() == null ? "" : threeGuaranteesPurExportData.getEnableNum();
            objs[19] = takeDecimals(threeGuaranteesPurExportData.getDetailTotalPrice());
            objs[20] = threeGuaranteesPurExportData.getServiceNo();
            objs[21] = threeGuaranteesPurExportData.getIsReturn();
            String actualReturn = threeGuaranteesPurExportData.getActualReturn();
            if (StringUtils.equals("0",actualReturn)) {
                objs[22] = "否";
            }else if(StringUtils.equals("1",actualReturn)){
                objs[22] = "是";
            }else{
                objs[22] = "";
            }

            objs[23] = threeGuaranteesPurExportData.getDeliveryReceiptTime() == null ? "" : sdf.format(threeGuaranteesPurExportData.getDeliveryReceiptTime());
            objs[24] = threeGuaranteesPurExportData.getFactoryNumber()==null ? "" : threeGuaranteesPurExportData.getFactoryNumber();
            objs[25] = threeGuaranteesPurExportData.getDeliveryQty()==null ? "0" : threeGuaranteesPurExportData.getDeliveryQty().toString();
            objs[26] = threeGuaranteesPurExportData.getRealQty()==null ? "0" : threeGuaranteesPurExportData.getRealQty().toString();
            Integer status = threeGuaranteesPurExportData.getStatus();
            String ckStatus = "";
            if (status.equals(0)) {
                ckStatus = "未出库";
            }
            if (status.equals(1)) {
                ckStatus = "部分出库";
            }
            if (status.equals(2)) {
                ckStatus = "已出库";
            }
            objs[27] = ckStatus;
            objs[28] = threeGuaranteesPurExportData.getReceiverAddress();
            objs[29] = threeGuaranteesPurExportData.getOutDate() == null ? "" : DateUtil.formatDateTime(threeGuaranteesPurExportData.getOutDate());
            objs[30] = threeGuaranteesPurExportData.getProdType();
            objs[31] = threeGuaranteesPurExportData.getMachineNumber();
            objs[32] = threeGuaranteesPurExportData.getCrmOrder();
            objs[33] = threeGuaranteesPurExportData.getServiceName();
            objs[34] = threeGuaranteesPurExportData.getServiceSite();
            Integer detailStatus = threeGuaranteesPurExportData.getDetailStatus();
            String ckDetailStatus = "";
            if (detailStatus.equals(0)) {
                ckDetailStatus = "未出库";
            }
            if (detailStatus.equals(1)) {
                ckDetailStatus = "部分出库";
            }
            if (detailStatus.equals(2)) {
                ckDetailStatus = "已出库";
            }
            objs[35] = ckDetailStatus;
            objs[36] = DateUtil.formatDateTime(threeGuaranteesPurExportData.getReceiveDate());
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public void exportAll(ThreeGuaranteesPurVO condition) throws Exception{
        condition.setBillNosList(xcmg.device.infra.StringUtil.splitList(condition.getBillNos()));
        // condition.setPurchaseNamesList(xcmg.device.infra.StringUtil.splitList(condition.getPurchaseNames()));
        if(!StringUtils.isEmpty(condition.getPurchaseNames())){
            List<String> purchaseNamesList = companyDealerService.listFullNamesByShortName(condition.getOrgId(),condition.getPurchaseNames());
            if(CollectionUtils.isEmpty(purchaseNamesList)){
                invokeExport(new ArrayList<>());
            }
            condition.setPurchaseNamesList(purchaseNamesList);
        }
        Integer count = threeGuaranteesPurMapper.findCountForExportAll(condition);
        List<ThreeGuaranteesPurAddVO> threeGuaranteesPurAddVO=new ArrayList<>();
        int times = count/500+1;
        for(int i=0; i<times; i++){
            PageHelperPlus.startPage(i + 1, 500, "APPLICATION_DATE DESC");
            List<ThreeGuaranteesPurDO> threeGuaranteesPurDO=threeGuaranteesPurMapper.list(condition);
            for(ThreeGuaranteesPurDO ThreeGuaranteesPurDO:threeGuaranteesPurDO){
                threeGuaranteesPurAddVO.add(this.item(ThreeGuaranteesPurDO.getId(),condition.getWarehouseCode()));
            }
        }
        invokeExport(threeGuaranteesPurAddVO);
    }

    private void invokeExport(List<ThreeGuaranteesPurAddVO> voList)throws Exception {
        String title = "三包申请导出";
        String[] rowsName = new String[]{"序号", "申请单号", "客户名称", "采购金额", "发货方式", "调度员",
                "审核人", "审核时间", "申请时间", "状态", "审核意见", "备注", "零件编码", "零件名称", "单位",
                "参考单价(￥)", "申请数量", "可用库存", "合计(￥)", "服务信息单号", "是否返厂", "发运时间", "序列号" ,
                "已建出库数量", "实际出库数量","出库状态","收货地址","出库时间"};
        List<Object[]> dataList = new ArrayList<Object[]>();
        int size;
        boolean fals;
        Object[] objs = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < voList.size(); i++) {
            ThreeGuaranteesPurVO e = voList.get(i).getHeaderInfo();
            if (!CollectionUtils.isEmpty(voList.get(i).getDetailList())) {
                size = voList.get(i).getDetailList().size();
                fals = true;
            } else {
                fals = false;
                size = 1;
            }
            for (int o = 0; o < size; o++) {
                objs = new Object[rowsName.length];
                objs[0] = i + 1;
                objs[1] = e.getPurchaseNo();
                objs[2] = e.getCustomerName();
                objs[3] = takeDecimals(e.getTotalPrice());
                objs[4] = e.getDeliveryTypeName();
                objs[5] = e.getDispatcherName();
                objs[6] = e.getRealAuditName() == null ? "" : e.getRealAuditName();
                objs[7] = e.getRealAuditDate() == null ? "" : DateUtil.formatDateTime(e.getRealAuditDate());
                objs[8] = DateUtil.formatDateTime(e.getApplicationDate());
                objs[9] = e.getStatusDesc();
                objs[10] = e.getAuditNote();
                objs[11] = e.getNote();
                if (fals) {
                    ThreeGuaranteesPurDetailVO v = voList.get(i).getDetailList().get(o);
                    objs[12] = v.getMaterialsNo();
                    objs[13] = v.getMaterialsDesc() == null ? "" : v.getMaterialsDesc();
                    objs[14] = v.getUnit() == null ? "" : v.getUnit();
                    objs[15] = v.getPrice() == null ? "" : v.getPrice();
                    objs[16] = v.getPurchaseQty() == null ? "" : v.getPurchaseQty();
                    objs[17] = v.getAmount() == null ? "" : v.getAmount();
                    objs[18] = v.getTotalPrice() == null ? "" : v.getTotalPrice();
                    objs[27] = v.getOutDate() == null ? "" : DateUtil.formatDateTime(v.getOutDate());
                }
                objs[19] = e.getServiceNo();
                objs[20] = e.getIsReturn();
                objs[21] = e.getDeliveryReceiptTime() == null ? "" : sdf.format(e.getDeliveryReceiptTime());
                objs[22] = e.getFactoryNumber()==null ? "" : e.getFactoryNumber();
                if (fals){
                    ThreeGuaranteesPurDetailVO v = voList.get(i).getDetailList().get(o);
                    objs[23] = v.getDeliveryQty()==null ? "0" : v.getDeliveryQty().toString();
                    objs[24] = v.getRealQty()==null ? "0" : v.getRealQty().toString();
                }
                Integer status = e.getStatus();
                String ckStatus = "";
                if (status.equals(0)) {
                    ckStatus = "未出库";
                }
                if (status.equals(1)) {
                    ckStatus = "部分出库";
                }
                if (status.equals(2)) {
                    ckStatus = "已出库";
                }
                objs[25] = ckStatus;
                objs[26] = e.getReceiverAddress();
                dataList.add(objs);
            }
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

//    private String getState(Integer state){
//        if(state == 0){
//            return "草稿";
//        }else if(state == 1){
//            return "待审核";
//        }else if(state == 2){
//            return "审核通过";
//        }else if(state == 3){
//            return "审核驳回";
//        }
//        return "";
//    }

    public static List<ThreeGuaranteesPurDetailVO> deRepeat(List<ThreeGuaranteesPurDetailVO> repeatList) {
        if(CollectionUtils.isEmpty(repeatList)){
            return repeatList;
        }
        for  ( int i  = 0 ; i< repeatList.size()-1;i++){
            BigDecimal sum =repeatList.get(i).getPurchaseQty();
            for  ( int j=repeatList.size()-1;j>i;j -- )  {
                if  (repeatList.get(j).equals(repeatList.get(i))||repeatList.get(j).getMaterialsNo().equals(repeatList.get(i).getMaterialsNo())){
                    sum=sum.add(repeatList.get(j).getPurchaseQty());
                    repeatList.remove(j);
                }
            }
            repeatList.get(i).setPurchaseQty(sum);
            repeatList.get(i).setTotalPrice(repeatList.get(i).getPrice()==null?new BigDecimal(0):repeatList.get(i).getPrice()
                    .multiply(repeatList.get(i).getPurchaseQty()));
        }
        return repeatList;
    }

    //导入
    public FunctionResult importExcel(InputStream in, String orgId) throws Exception{
        FunctionResult result=new FunctionResult();
        HSSFWorkbook wb=new HSSFWorkbook(in);
        HSSFSheet sheet=wb.getSheetAt(0);

        int totalRow=sheet.getLastRowNum();
        if(totalRow<3){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell=sheet.getRow(2).getLastCellNum();
        if(totalCell!=4){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        List<ThreeGuaranteesPurDetailVO> detailVOList=new ArrayList<>();
        List<ThreeGuaranteesPurDetailVO> errorDetailVOList=new ArrayList<>();
        for (int i=3;i<=totalRow;i++){
            HSSFRow curRow=sheet.getRow(i);
            ThreeGuaranteesPurDetailVO detailVO=new ThreeGuaranteesPurDetailVO();
            if(curRow==null){
                continue;
            }
            if(isRowEmpty(curRow)){
                continue;
            }
            String materialsNo=excelValue(curRow,1);
            String qty=excelValue(curRow,3);
            //String materialsNo= curRow.getCell(1)==null?"": ExcelUtil.getCellStringValue(curRow.getCell(1));
            //String qty=curRow.getCell(3)==null?"1":ExcelUtil.getCellStringValue(curRow.getCell(3));
            if(!isInteger(qty) || "0".equals(qty)){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("入库数量格式不正确");
                errorDetailVOList.add(detailVO);
                continue;
            }
            if(new BigDecimal(qty).compareTo(BigDecimal.valueOf(99999999.99)) > 0){
                detailVO.setErrorRow(i+1);
                detailVO.setRemark("入库数量过大");
                errorDetailVOList.add(detailVO);
                continue;
            }
            MaterialsVO materialsVO=materialsService.itemByNo(materialsNo,orgId);
            if(materialsVO==null){

                detailVO.setErrorRow(i+1);
                detailVO.setRemark("零件不存在");
                errorDetailVOList.add(detailVO);
                continue;
            }
            BigDecimal intQty = new BigDecimal(qty);
            BigDecimal max = new BigDecimal(99999999.99);
            if(intQty.compareTo(max) > 0){
                intQty = max;
            }
            detailVO.setPurchaseQty(intQty);
            detailVO.setMaterialsNo(materialsVO.getMaterialsNo());
            detailVO.setMaterialsDesc(materialsVO.getMaterialsDes());
            detailVO.setPrice(materialsVO.getPrice());
            detailVO.setUnit(materialsVO.getUnit());
            detailVO.setPurchaseQty(intQty);
            detailVO.setIsMinimumBuy(materialsVO.getIsMinimumBuy());
            detailVO.setMinimumBuy(materialsVO.getMinimumBuy());
            detailVO.setTotalPrice(detailVO.getPrice()==null?new BigDecimal(0):detailVO.getPrice()
                    .multiply(detailVO.getPurchaseQty()));

            detailVOList.add(detailVO);
        }
        Map<String, BigDecimal> map = new HashMap<>();
        WarehouseInventoryVO request=new WarehouseInventoryVO();
        request.setOrgId(orgId);
        List<WarehouseInventoryDO> warehouseInventoryList=warehouseInventoryMapper.listForMaterial(request);
        for (WarehouseInventoryDO e:warehouseInventoryList) {
            map.put(e.getMaterialNo(), e.getAmount());
        }
        for(int i=0;i<detailVOList.size();i++){
            if(map.containsKey(detailVOList.get(i).getMaterialsNo())){
                detailVOList.get(i).setAmount(map.get(detailVOList.get(i).getMaterialsNo()));
            }else{
                detailVOList.get(i).setAmount(BigDecimal.ZERO);
            }
        }


        if(ListUtil.isNullOrEmpty(errorDetailVOList)){
            result.setValue(deRepeat(detailVOList));
            result.setCode(ErrorCode.Success);
        }
        else {
            result.setValue(errorDetailVOList);
            result.setCode(ErrorCode.IllegalArument);
        }
        return result;
    }

    private String excelValue(HSSFRow curRow,Integer line){
        Cell cell = curRow.getCell(line);
        String cellValue="";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue());
                    break;

                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;

                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;

                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    cellValue = cell.getCellFormula() + "";
                    break;

                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;

                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "";
                    break;

                default:
                    cellValue = "";
                    break;
            }
        }
        return cellValue;
    }

    private boolean isInteger(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        try {
            BigDecimal decimal = new BigDecimal(str);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    public static boolean isRowEmpty(HSSFRow row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            HSSFCell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK&&!StringUtil.isNullOrSpace(ExcelUtil.getCellStringValue(cell)))
            {
                return false;
            }
        }
        return true;
    }

    public void download() throws Exception{
        FileUtil.downLoadFile(response,filePath,templateExcelFileName);
    }

    /**
     * @Author: WangKe
     * @Description: 出库时更新三包申请单状态
     * @Date: 2018/3/14 0014
     */
    public boolean updateByOutBound(String saleNo, String materailNo, BigDecimal outAmount, String orgId){
        ThreeGuaranteesPurVO threeGuaranteesPurVO = new ThreeGuaranteesPurVO();
        threeGuaranteesPurVO.setOrgId(orgId);
        threeGuaranteesPurVO.setPurchaseNo(saleNo);
        List<ThreeGuaranteesPurDO> threeGuaranteesPurList = threeGuaranteesPurMapper.list(threeGuaranteesPurVO);
        if(ListUtil.isNullOrEmpty(threeGuaranteesPurList)){
            return false;
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurList.get(0);
        ThreeGuaranteesPurDetailDO detailDO = threeGuaranteesPurDetailMapper.findByNo(threeGuaranteesPurDO.getId(), materailNo);
        if(detailDO == null){
            return false;
        }
        detailDO.setRealQty(detailDO.getRealQty().add(outAmount));
        if(detailDO.getRealQty().compareTo(detailDO.getPurchaseQty()) >= 0){
            detailDO.setStatus(2);
        }else{
            detailDO.setStatus(1);
        }
        //记录出库时间
        Date outDate = new Date();//出库时间
        detailDO.setOutDate(outDate);

        boolean success = threeGuaranteesPurDetailMapper.update(detailDO)>0;
        if(!success){
            return false;
        }
        //更新三包申请主表出库状态
        Integer status = 1;
        if(detailDO.getStatus() == 2){
            List<ThreeGuaranteesPurDetailDO> detailDOList = threeGuaranteesPurDetailMapper.list(threeGuaranteesPurDO.getId());
            if(ListUtil.isNullOrEmpty(detailDOList)){
                return false;
            }
            status = 2;
            for(ThreeGuaranteesPurDetailDO intentionDetailDO : detailDOList){
                if(!intentionDetailDO.getMaterialsNo().equals(materailNo) && intentionDetailDO.getStatus() != 2){
                    status = 1;
                    break;
                }
            }
        }
        if(status != null && status.compareTo(2) == 0){
            threeGuaranteesPurDO.setOutDate(outDate);
        }
        threeGuaranteesPurDO.setStatus(status);
        return threeGuaranteesPurMapper.update(threeGuaranteesPurDO)>0;
    }

    /**
     * @Author: WangKe
     * @Description: 三包出库单手动结单时更新三包申请单状态
     * @Date: 2018/6/4 0004
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByManulFinish(ThreeGuaranteesOutDO outDO, String materialNo, String orgId)throws Exception{
        if(outDO == null){
            return false;
        }
        List<ThreeGuaranteesOutDetailDO> outDetailDOList = threeGuaranteesOutDetailMapper.list(outDO.getId());
        if(ListUtil.isNullOrEmpty(outDetailDOList)){
            return false;
        }

        ThreeGuaranteesPurVO threeGuaranteesPurVO = new ThreeGuaranteesPurVO();
        threeGuaranteesPurVO.setOrgId(orgId);
        threeGuaranteesPurVO.setPurchaseNo(outDO.getPurchaseNo());
        List<ThreeGuaranteesPurDO> threeGuaranteesPurList = threeGuaranteesPurMapper.list(threeGuaranteesPurVO);
        if(ListUtil.isNullOrEmpty(threeGuaranteesPurList)){
            return false;
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurList.get(0);
        List<ThreeGuaranteesPurDetailDO> purDetailDOList = threeGuaranteesPurDetailMapper.list(threeGuaranteesPurDO.getId());
        if(ListUtil.isNullOrEmpty(purDetailDOList)){
            return false;
        }

        BigDecimal sub;
        boolean success;
        boolean enable;
        for(ThreeGuaranteesPurDetailDO purDetailDO : purDetailDOList){
            if(!StringUtil.isNullOrEmpty(materialNo) && !materialNo.equals(purDetailDO.getMaterialsNo())){
                continue;
            }
            for(ThreeGuaranteesOutDetailDO outDetailDO : outDetailDOList){
                if(purDetailDO.getMaterialsNo().equals(outDetailDO.getMaterialsNo()) ){
                    outDetailDO.setOutLocationStatus(outDetailDO.getOutLocationStatus()==null?0:outDetailDO.getOutLocationStatus());
                    enable = outDetailDO.getOutLocationStatus() != 2 && outDetailDO.getOutLocationStatus() != 3;
                    if(enable){
                        sub = outDetailDO.getDeliveryQty().subtract(outDetailDO.getRealOutQty());
                        purDetailDO.setDeliveryQty(purDetailDO.getDeliveryQty().subtract(sub));
                        success = threeGuaranteesPurDetailMapper.update(purDetailDO)>0;
                        if(!success){
                            throw new Exception("更新三包申请详情失败");
                        }

                        //更新其他三包出库单的已发货数量
                        success = threeGuaranteesOutDetailMapper.updateOutQty(orgId, purDetailDO.getDeliveryQty(),
                                threeGuaranteesPurDO.getPurchaseNo(), purDetailDO.getMaterialsNo()) > 0;
                        if(!success){
                            throw new Exception("更新三包申请详情失败");
                        }
                    }
                }
            }
        }

        threeGuaranteesPurDO.setOutEnable(1);
        return threeGuaranteesPurMapper.update(threeGuaranteesPurDO)>0;
    }

    /**
     * @Author: WangKe
     * @Description: 更新三包申请详情发货数量
     * @Date: 2018/3/14 0014
     */
    public boolean updateDetailQty(String purchaseNo, String materialNo, BigDecimal qty, String orgId){
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurMapper.itemByNo(purchaseNo, orgId);
        if(threeGuaranteesPurDO == null){
            return false;
        }
        ThreeGuaranteesPurDetailDO detailDO = threeGuaranteesPurDetailMapper.findByNo(threeGuaranteesPurDO.getId(), materialNo);
        if(detailDO == null){
            return false;
        }
        detailDO.setDeliveryQty(qty);
        return threeGuaranteesPurDetailMapper.update(detailDO)>0;
    }

    /**
     * 设置三包申请单状态<br>
     *     根据已出数量判断申请单是否还可以出库
     * @param purchaseNo String
     * @return ErrorCode
     */
    public boolean resetPurchaseStatus(String purchaseNo,String orgId)
    {
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurMapper.itemByNo(purchaseNo, orgId);

        List<ThreeGuaranteesPurDetailDO> listDO = threeGuaranteesPurDetailMapper.list(threeGuaranteesPurDO.getId());
        if(ListUtil.isNullOrEmpty(listDO)){
            return false;
        }
        boolean tempFlag = true;//默认true为可出库状态


        for (ThreeGuaranteesPurDetailDO entity : listDO)
        {
            //如果申请数量等于出库数量，则标志位true
            if (!entity.getPurchaseQty().equals(entity.getDeliveryQty()))
            {
                tempFlag = false;
            }
        }
        ThreeGuaranteesPurDO updateBean = new ThreeGuaranteesPurDO();
        updateBean.setId(threeGuaranteesPurDO.getId());
        if (tempFlag)
        {
            //申请数量等于出库数量，设置状态为不可出库
            updateBean.setOutEnable(2);
        }
        else
        {
            //可出库
            updateBean.setOutEnable(1);
        }
        return threeGuaranteesPurMapper.update(updateBean)>0;
    }


    public  ThreeGuaranteesPurDO itemByNo(String billNo,String orgId){
        return threeGuaranteesPurMapper.itemByNo(billNo, orgId);
    }

    public  ThreeGuaranteesPurDO itemByPurNo(String billNo,String orgId){
        ThreeGuaranteesPurDO purDO = threeGuaranteesPurMapper.itemByNo(billNo, orgId);
        // 这里有个坑，billNo实际上传的是主表的id，并不是No
        List<ThreeGuaranteesPurDetailDO> purDetailDOs = threeGuaranteesPurDetailMapper.list(purDO.getId());
        purDO.setPurDetailDOS(purDetailDOs);
        return purDO;
    }

    private ActionResult getResult(ErrorCode errorCode, String value) {
        return new ActionResult(errorCode.getCode(), errorCode.getDesc(), value);
    }

    private ActionResult getErrorResult(int errotCode,String msg){
        return new ActionResult(errotCode,msg);
    }

    /**
     * 添加三包申请（外部接口调用）
     *
     * @param model
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ActionResult addThreeGuaranteesPur(ThreeGuaranteesPurAddVO model,CompanyInfoDO companyInfo) throws Exception {
        Integer count = threeGuaranteesPurMapper.countByCrmOrder(model.getHeaderInfo().getCrmOrder());
        if (null != count && count > 0) {
            LogHelper.monitor("crmOrder已存在");
            return getErrorResult(ErrorCode.Failure.getCode(), "crmOrder已存在");
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        ThreeGuaranteesPurVO purVO = model.getHeaderInfo();
        if (StringUtils.isBlank(purVO.getReceiverPhone())) {
            throw new Exception("收货人电话不能为空");
        }
        if (StringUtils.isBlank(purVO.getReceiverAddress())) {
            throw new Exception("收货人地址不能为空");
        }
        BeanUtils.copyProperties(purVO, threeGuaranteesPurDO);
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return getResult(ErrorCode.IllegalArument, "获取GUID出错");
        }
        String orgId = companyInfo.getOrgId();
        String purchaseNo = genDocumentService.genDocumentNo(BillDesc.Purchase, orgId);
        threeGuaranteesPurDO.setId(text.getValue());
        threeGuaranteesPurDO.setPurchaseNo(purchaseNo);
        rounding(threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setTotalPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setOrgId(orgId);
        threeGuaranteesPurDO.setStatus(0);
        //塔机的直接取调用者传过来的数据，其他的走以前的逻辑
        String sapCode = purVO.getSapCode();
        if(sapCode != null && "2130".equals(sapCode)){
        }else{
            threeGuaranteesPurDO.setGuaraenteesStatus(GuaraenteesStatus.Saved.toString());
        }

        threeGuaranteesPurDO.setApplicationDate(new Date());
        threeGuaranteesPurDO.setMachineNumber(purVO.getMachineNumber());
        threeGuaranteesPurDO.setSapId(purVO.getSapName());

        //施维英字段
        threeGuaranteesPurDO.setProdType(purVO.getProdType());
        threeGuaranteesPurDO.setServiceNo(purVO.getServiceNo());
        threeGuaranteesPurDO.setCrmOrder(purVO.getCrmOrder());
        threeGuaranteesPurDO.setServiceName(purVO.getServiceName());
        threeGuaranteesPurDO.setServiceSite(purVO.getServiceSite());

        //备件指令字段
        threeGuaranteesPurDO.setArrivalTime(purVO.getArrivalTime());
        threeGuaranteesPurDO.setFactoryNumber(purVO.getFactoryNumber());
        threeGuaranteesPurDO.setServicePhone(purVO.getServicePhone());
        threeGuaranteesPurDO.setIsReturn(purVO.getIsReturn());

        //crm备注
        threeGuaranteesPurDO.setNote(purVO.getNote());
        if ("2050".equals(purVO.getSapCode())) {
            threeGuaranteesPurDO.setSapName("20000321");
            threeGuaranteesPurDO.setSapTypeName("Z01");
            threeGuaranteesPurDO.setGuaraenteesStatus("2");
            threeGuaranteesPurDO.setSapId("20000321");
        }


        if (StringUtils.isNotBlank(purVO.getCustomerSapCode())) {
            CompanyDealerDO companyDealerDO=companyDealerMapper.itemByDealerCode(threeGuaranteesPurDO.getOrgId(),purVO.getCustomerSapCode());
            if( null != companyDealerDO) {
                threeGuaranteesPurDO.setCustomerId(companyDealerDO.getId().toString());
                threeGuaranteesPurDO.setCustomerName(companyDealerDO.getCompanyName());
            }
        }
        else {
            threeGuaranteesPurDO.setCustomerName(purVO.getCustomerName());
//            throw new Exception("客户编号不能为空");
        }
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(GuaraenteesStatus.Name.toString(), threeGuaranteesPurDO.getGuaraenteesStatus());
        if (auditDataDictionaryDO != null) {
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        BigDecimal purQty = BigDecimal.ZERO;
        for (ThreeGuaranteesPurDetailVO detailVO : model.getDetailList()) {
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO, threeGuaranteesPurDetailDO);
            threeGuaranteesPurDetailDO.setBarcode(detailVO.getBarcode());
            ActionResult<String> textScheduleDetail = fastGenClient.textGuid();
            if (textScheduleDetail.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("获取GUID出错");
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailVO.getMaterialsNo(), orgId);
            if(materialsDO!=null){
                threeGuaranteesPurDetailDO.setMaterialsDesc(materialsDO.getMaterialsDes());
                threeGuaranteesPurDetailDO.setUnit(materialsDO.getUnit());
            }
            threeGuaranteesPurDetailDO.setDeliveryQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setStatus(0);
            threeGuaranteesPurDetailDO.setRealQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            threeGuaranteesPurDetailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            threeGuaranteesPurDetailDO.setCreateDate(threeGuaranteesPurDO.getApplicationDate());
            threeGuaranteesPurDetailDO.setPrice(rounding(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        if (threeGuaranteesPurMapper.add(threeGuaranteesPurDO) > 0) {
            return getResult(ErrorCode.Success, purchaseNo);
        }
        return getResult(ErrorCode.Failure, "插入数据失败");
    }


    /**
     * 添加三包申请（塔机调用）
     *
     * @param model
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ActionResult addThreeGuaranteesPur4Tj(ThreeGuaranteesPurAddVO model) throws Exception {
        Integer count = threeGuaranteesPurMapper.countByCrmOrder(model.getHeaderInfo().getCrmOrder());
        if (null != count && count > 0) {
            LogHelper.monitor("crmOrder已存在");
            return getErrorResult(ErrorCode.Failure.getCode(), "crmOrder已存在");
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        ThreeGuaranteesPurVO purVO = model.getHeaderInfo();
        if (StringUtils.isBlank(purVO.getReceiverPhone())) {
            throw new Exception("收货人电话不能为空");
        }
        if (StringUtils.isBlank(purVO.getReceiverAddress())) {
            throw new Exception("收货人地址不能为空");
        }
        BeanUtils.copyProperties(purVO, threeGuaranteesPurDO);
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return getResult(ErrorCode.IllegalArument, "获取GUID出错");
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(purVO.getSapCode());
        if (null == companyInfoDO) {
            return getResult(ErrorCode.Failure, "sapCode不存在");
        }

        String purchaseNo = genDocumentService.genDocumentNo(BillDesc.Purchase, companyInfoDO.getOrgId());
        threeGuaranteesPurDO.setId(text.getValue());
        threeGuaranteesPurDO.setPurchaseNo(purchaseNo);
        rounding(threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setTotalPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setOrgId(companyInfoDO.getOrgId());
        threeGuaranteesPurDO.setStatus(0);
        //塔机的直接取调用者传过来的数据，其他的走以前的逻辑
        String sapCode = purVO.getSapCode();
        if(sapCode != null && "2130".equals(sapCode)){
        }else{
            threeGuaranteesPurDO.setGuaraenteesStatus(GuaraenteesStatus.Saved.toString());
        }

        threeGuaranteesPurDO.setApplicationDate(new Date());
        threeGuaranteesPurDO.setMachineNumber(purVO.getMachineNumber());
        threeGuaranteesPurDO.setSapId(purVO.getSapId());

        //施维英字段
        threeGuaranteesPurDO.setProdType(purVO.getProdType());
        threeGuaranteesPurDO.setServiceNo(purVO.getServiceNo());
        threeGuaranteesPurDO.setCrmOrder(purVO.getCrmOrder());
        threeGuaranteesPurDO.setServiceName(purVO.getServiceName());
        threeGuaranteesPurDO.setServiceSite(purVO.getServiceSite());

        //备件指令字段
        threeGuaranteesPurDO.setArrivalTime(purVO.getArrivalTime());
        threeGuaranteesPurDO.setFactoryNumber(purVO.getFactoryNumber());
        threeGuaranteesPurDO.setServicePhone(purVO.getServicePhone());
        threeGuaranteesPurDO.setIsReturn(purVO.getIsReturn());

        //crm备注
        threeGuaranteesPurDO.setNote(purVO.getNote());
        if ("2050".equals(purVO.getSapCode())) {
            threeGuaranteesPurDO.setSapName("20000321");
            threeGuaranteesPurDO.setSapTypeName("Z01");
            threeGuaranteesPurDO.setGuaraenteesStatus("2");
            threeGuaranteesPurDO.setSapId("20000321");
        }


        if (StringUtils.isNotBlank(purVO.getCustomerSapCode())) {
            CompanyDealerDO companyDealerDO=companyDealerMapper.itemByDealerCode(threeGuaranteesPurDO.getOrgId(),purVO.getCustomerSapCode());
            if( null != companyDealerDO) {
                threeGuaranteesPurDO.setCustomerId(companyDealerDO.getId().toString());
                threeGuaranteesPurDO.setCustomerName(companyDealerDO.getCompanyName());
            }
        }
        else {
            threeGuaranteesPurDO.setCustomerName(purVO.getCustomerName());
//            throw new Exception("客户编号不能为空");
        }
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(GuaraenteesStatus.Name.toString(), threeGuaranteesPurDO.getGuaraenteesStatus());
        if (auditDataDictionaryDO != null) {
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        BigDecimal purQty = BigDecimal.ZERO;
        for (ThreeGuaranteesPurDetailVO detailVO : model.getDetailList()) {
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO, threeGuaranteesPurDetailDO);
            threeGuaranteesPurDetailDO.setBarcode(detailVO.getBarcode());
            ActionResult<String> textScheduleDetail = fastGenClient.textGuid();
            if (textScheduleDetail.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("获取GUID出错");
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailVO.getMaterialsNo(), companyInfoDO.getOrgId());
            if(materialsDO!=null){
                threeGuaranteesPurDetailDO.setMaterialsDesc(materialsDO.getMaterialsDes());
                threeGuaranteesPurDetailDO.setUnit(materialsDO.getUnit());
            }
            threeGuaranteesPurDetailDO.setDeliveryQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setStatus(0);
            threeGuaranteesPurDetailDO.setRealQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            threeGuaranteesPurDetailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            threeGuaranteesPurDetailDO.setCreateDate(threeGuaranteesPurDO.getApplicationDate());
            threeGuaranteesPurDetailDO.setPrice(rounding(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        if (threeGuaranteesPurMapper.add(threeGuaranteesPurDO) > 0) {
            return getResult(ErrorCode.Success, purchaseNo);
        }
        return getResult(ErrorCode.Failure, "插入数据失败");
    }

    /**
     * @Author: WangKe
     * @Description: 三包冲销入库时更新三包申请单
     * @Date: 2018/7/11 0015
     */
    public boolean updateByThreeReverse(ThreeGuaranteesOutDO outDO, String orgId)throws Exception{
        if(outDO == null){
            return false;
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = threeGuaranteesPurMapper.itemByNo(outDO.getPurchaseNo(), orgId);
        if(threeGuaranteesPurDO == null){
            return false;
        }
        //获取三包出库详情
        List<ThreeGuaranteesOutDetailDO> noteDetailDOList = threeGuaranteesOutDetailMapper.list(outDO.getId());
        if(ListUtil.isNullOrEmpty(noteDetailDOList)){
            return false;
        }
        //将三包申请单的零件编码放到list中
        List<String> materialNoList = new ArrayList<>();
        List<ThreeGuaranteesPurDetailDO> intentionDetailDOList = threeGuaranteesPurDetailMapper.list(threeGuaranteesPurDO.getId());
        if(ListUtil.isNullOrEmpty(intentionDetailDOList)){
            return false;
        }
        for(ThreeGuaranteesPurDetailDO purDetailDO : intentionDetailDOList){
            materialNoList.add(purDetailDO.getMaterialsNo());
        }
        //更新三包申请单详情中涉及到的零件
        boolean success;
        Integer inventeryStatus = 0;
        for(ThreeGuaranteesOutDetailDO outDetailDO : noteDetailDOList){
            ThreeGuaranteesPurDetailDO purDetailDO = threeGuaranteesPurDetailMapper.findByNo(threeGuaranteesPurDO.getId(), outDetailDO.getMaterialsNo());
            if(purDetailDO == null){
                return false;
            }
            //过滤出未被涉及到的零件
            if(materialNoList.contains(outDetailDO.getMaterialsNo())){
                materialNoList.remove(outDetailDO.getMaterialsNo());
            }
            purDetailDO.setDeliveryQty(purDetailDO.getDeliveryQty().subtract(outDetailDO.getDeliveryQty()));
            purDetailDO.setRealQty(purDetailDO.getRealQty().subtract(outDetailDO.getRealOutQty()));
            if(purDetailDO.getDeliveryQty().compareTo(BigDecimal.ZERO) <= 0){
                purDetailDO.setDeliveryQty(new BigDecimal(0));
            }
            if(purDetailDO.getRealQty().compareTo(BigDecimal.ZERO) <= 0){
                purDetailDO.setRealQty(new BigDecimal(0));
                purDetailDO.setStatus(0);
            }else{
                purDetailDO.setStatus(1);
                inventeryStatus = 1;
            }
            success = threeGuaranteesPurDetailMapper.update(purDetailDO)>0;
            if(!success){
                return false;
            }
            //更新其他三包出库单的已发货数量
            threeGuaranteesOutDetailMapper.updateOutQty(orgId, purDetailDO.getDeliveryQty(),
                    outDO.getPurchaseNo(), outDetailDO.getMaterialsNo());
        }
        if(inventeryStatus == 0 && !ListUtil.isNullOrEmpty(materialNoList)){
            for(String materialNo : materialNoList){
                ThreeGuaranteesPurDetailDO purDetailDO = threeGuaranteesPurDetailMapper.findByNo(threeGuaranteesPurDO.getId(), materialNo);
                if(purDetailDO == null){
                    return false;
                }
                if(purDetailDO.getRealQty().compareTo(BigDecimal.ZERO) > 0){
                    inventeryStatus = 1;
                    break;
                }
            }
        }
        threeGuaranteesPurDO.setOutEnable(1);
        threeGuaranteesPurDO.setStatus(inventeryStatus);
        success = threeGuaranteesPurMapper.update(threeGuaranteesPurDO)>0;
        return success;
    }

    public PageCommonVO<ThreeGuaranteesPurAllDetailVO> listDetail(SearchCommonVO<ThreeGuaranteesPurDetailQueryVO> condition) {
        PageCommonVO<ThreeGuaranteesPurAllDetailVO> result = new PageCommonVO();
        //准备额外的查询条件
        condition.getFilters().setBillNosList(xcmg.device.infra.StringUtil.getStrSplitList(condition.getFilters().getBillNos()));
        if(!StringUtils.isEmpty(condition.getFilters().getPurchaseNames())){
            List<String> purchaseNamesList = companyDealerService.listFullNamesByShortName(condition.getFilters().getOrgId(), condition.getFilters().getPurchaseNames());
            if (CollectionUtils.isEmpty(purchaseNamesList)) {
                result.setPageInfo(new PageInfo(new ArrayList()));
                result.setPageInfoList(new ArrayList());
                return result;
            }
            condition.getFilters().setPurchaseNamesList(purchaseNamesList);
        }
        String warehouseCode = condition.getFilters().getWarehouseCode();

//        PageHelperPlus.orderBy("application_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<ThreeGuaranteesPurAllDetailVO> list = threeGuaranteesPurDetailMapper.listDetail(condition.getFilters());


        for (ThreeGuaranteesPurAllDetailVO model : list) {
            if (model.getPrice() != null) {
                model.setPrice(model.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
            }
            if (model.getTotalPrice() != null) {
                model.setTotalPrice(model.getTotalPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
            }
            if(model.getHeaderPrice()!=null){
                model.setHeaderPrice(model.getHeaderPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
            }
            if(model.getHeaderTotalPrice()!=null){
                model.setHeaderTotalPrice(model.getHeaderTotalPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
            }

            EnableAndOccupyVO enableAndOccupyVO = warehouseInventoryService.findEnableAndOccupyNum(model.getMaterialsNo(), model.getOrgid(), warehouseCode);
            BeanUtils.copyProperties(enableAndOccupyVO, model);
            model.setAmount(enableAndOccupyVO.getEnableNum());
        }
        result.setPageInfo(new PageInfo(list));
        result.setPageInfoList(list);
        return result;
    }

    public CompanyDealerDO getCompanyDealer(String orgId,String customerSapCode){
        CompanyDealerDO companyDealerDO=companyDealerMapper.itemByDealerCode(orgId,customerSapCode);
        return companyDealerDO;
    }

    /**
     * 根据crm单号获取申请单
     * @param crmOrder
     * @return
     */
    public List<ThreeGuaranteesPurDO> getPurByCrmOrder(String crmOrder){
        if(StringUtils.isEmpty(crmOrder)){
            return null;
        }
        List<ThreeGuaranteesPurDO> threeGuaranteesPurDOS = threeGuaranteesPurMapper.selectByCrmOrder(crmOrder);
        if(CollectionUtils.isEmpty(threeGuaranteesPurDOS)){
            return null;
        }
        return threeGuaranteesPurDOS;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer updateByCrmOrder(ThreeGuaranteesPurDO threeGuaranteesPurDO){
        return threeGuaranteesPurMapper.updateByCrmOrder(threeGuaranteesPurDO);
    }

    /**
     * 添加三包申请（铲运调用）
     *
     * @param model
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ActionResult addThreeGuaranteesPur4Cy(ThreeGuaranteesPurAddVO model) throws Exception {
        Integer count = threeGuaranteesPurMapper.countByCrmOrder(model.getHeaderInfo().getCrmOrder());
        if (null != count && count > 0) {
            LogHelper.monitor("crmOrder已存在");
            return getErrorResult(ErrorCode.Failure.getCode(), "crmOrder已存在");
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        ThreeGuaranteesPurVO purVO = model.getHeaderInfo();
        if (StringUtils.isBlank(purVO.getReceiverPhone())) {
            throw new Exception("收货人电话不能为空");
        }
        if (StringUtils.isBlank(purVO.getReceiverAddress())) {
            throw new Exception("收货人地址不能为空");
        }
        BeanUtils.copyProperties(purVO, threeGuaranteesPurDO);
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return getResult(ErrorCode.IllegalArument, "获取GUID出错");
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(purVO.getSapCode());
        if (null == companyInfoDO) {
            return getResult(ErrorCode.Failure, "sapCode不存在");
        }

        String purchaseNo = genDocumentService.genDocumentNo(BillDesc.Purchase, companyInfoDO.getOrgId());
        threeGuaranteesPurDO.setId(text.getValue());
        threeGuaranteesPurDO.setPurchaseNo(purchaseNo);
        rounding(threeGuaranteesPurDO);
        threeGuaranteesPurDO.setPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setTotalPrice(BigDecimal.ZERO);
        threeGuaranteesPurDO.setOrgId(companyInfoDO.getOrgId());
        threeGuaranteesPurDO.setStatus(0);
        //塔机的直接取调用者传过来的数据，其他的走以前的逻辑
        String sapCode = purVO.getSapCode();
        if(sapCode != null && "2130".equals(sapCode)){
        }else{
            threeGuaranteesPurDO.setGuaraenteesStatus(GuaraenteesStatus.Saved.toString());
        }

        threeGuaranteesPurDO.setApplicationDate(new Date());
        threeGuaranteesPurDO.setMachineNumber(purVO.getMachineNumber());
        threeGuaranteesPurDO.setSapId(purVO.getSapId());

        //施维英字段
        threeGuaranteesPurDO.setProdType(purVO.getProdType());
        threeGuaranteesPurDO.setServiceNo(purVO.getServiceNo());
        threeGuaranteesPurDO.setCrmOrder(purVO.getCrmOrder());
        threeGuaranteesPurDO.setServiceName(purVO.getServiceName());
        threeGuaranteesPurDO.setServiceSite(purVO.getServiceSite());

        //备件指令字段
        threeGuaranteesPurDO.setArrivalTime(purVO.getArrivalTime());
        threeGuaranteesPurDO.setFactoryNumber(purVO.getFactoryNumber());
        threeGuaranteesPurDO.setServicePhone(purVO.getServicePhone());
        threeGuaranteesPurDO.setIsReturn(purVO.getIsReturn());

        //crm备注
        threeGuaranteesPurDO.setNote(purVO.getNote());
        if ("2050".equals(purVO.getSapCode())) {
            threeGuaranteesPurDO.setSapName("20000321");
            threeGuaranteesPurDO.setSapTypeName("Z01");
            threeGuaranteesPurDO.setGuaraenteesStatus("2");
            threeGuaranteesPurDO.setSapId("20000321");
        }
        //客户编号名称
        if (StringUtils.isNotBlank(purVO.getCustomerSapCode())) {
            CompanyDealerDO companyDealerDO=companyDealerMapper.itemByDealerCode(threeGuaranteesPurDO.getOrgId(),purVO.getCustomerSapCode());
            if( null != companyDealerDO) {
                threeGuaranteesPurDO.setCustomerId(companyDealerDO.getId().toString());
                threeGuaranteesPurDO.setCustomerName(companyDealerDO.getCompanyName());
            }
        }
        else {
            threeGuaranteesPurDO.setCustomerName(purVO.getCustomerName());
        }
        DataDictionaryDO auditDataDictionaryDO = dataDictionaryMapper.itemByCode(GuaraenteesStatus.Name.toString(), threeGuaranteesPurDO.getGuaraenteesStatus());
        if (auditDataDictionaryDO != null) {
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        BigDecimal purQty = BigDecimal.ZERO;
        for (ThreeGuaranteesPurDetailVO detailVO : model.getDetailList()) {
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            BeanUtils.copyProperties(detailVO, threeGuaranteesPurDetailDO);
            threeGuaranteesPurDetailDO.setBarcode(detailVO.getBarcode());
            ActionResult<String> textScheduleDetail = fastGenClient.textGuid();
            if (textScheduleDetail.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("获取GUID出错");
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(detailVO.getMaterialsNo(), companyInfoDO.getOrgId());
            if(materialsDO!=null){
                threeGuaranteesPurDetailDO.setMaterialsDesc(materialsDO.getMaterialsDes());
                threeGuaranteesPurDetailDO.setUnit(materialsDO.getUnit());
            }
            threeGuaranteesPurDetailDO.setDeliveryQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setStatus(0);
            threeGuaranteesPurDetailDO.setRealQty(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setCreateId(threeGuaranteesPurDO.getApplicationId());
            threeGuaranteesPurDetailDO.setCreateName(threeGuaranteesPurDO.getApplicationName());
            threeGuaranteesPurDetailDO.setCreateDate(threeGuaranteesPurDO.getApplicationDate());
            threeGuaranteesPurDetailDO.setPrice(rounding(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        if (threeGuaranteesPurMapper.add(threeGuaranteesPurDO) > 0) {
            return getResult(ErrorCode.Success, purchaseNo);
        }
        return getResult(ErrorCode.Failure, "插入数据失败");
    }

    /**
    * @Desc   更新三包申请详情发货数量(铲运)
    * @Author Mr.dong
    * @Date   2020/12/16 14:27
    */
    public boolean updateDetailQty4Cy(String purId, String materialNo, BigDecimal qty){
        ThreeGuaranteesPurDetailDO detailDO = threeGuaranteesPurDetailMapper.findByNo(purId, materialNo);
        if(detailDO == null){
            return false;
        }
        detailDO.setDeliveryQty(qty);
        return threeGuaranteesPurDetailMapper.update(detailDO)>0;
    }


    @Transactional
    public ActionResult synJCThreeGuarantees(ThreeGuaranteesPurJCAddVO model) throws Exception {
        ThreeGuaranteesPurJCAddHeadInfo headInfo = model.getHeadInfo();
        if (null == model || null == headInfo || model.getDetailList().isEmpty()) {
            return ActionResultUtil.errorActionResult(ErrorCode.IllegalArument);
        }
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(CompanyUtil.JC_SAP_CODE);
        ActionResult<String> result = addJCThreeGuaranteesPur(model,companyInfoDO);
        if(!ActionResultUtil.judgeSuccess(result)){
            throw new Exception(result.getMessage());
        }
        //自动创建出库单
        String purchaseNo = result.getValue();
        threeGuaranteesOutService.jcAutoAddThreeGuaranteesOut(purchaseNo,companyInfoDO);
        return result;
    }

    /**
     * @Des 基础crm同步创建三包申请单
     * @Date 2021/5/28 10:32
     * @Author wangzhaoyu
     * @Param [model, companyInfoDO]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
    private ActionResult addJCThreeGuaranteesPur(ThreeGuaranteesPurJCAddVO model,CompanyInfoDO companyInfoDO) throws Exception {
        ThreeGuaranteesPurJCAddHeadInfo headInfo = model.getHeadInfo();
        String crmOrder = headInfo.getCrmOrder();
        Integer count = threeGuaranteesPurMapper.countByCrmOrder(crmOrder);
        if (null != count && count > 0) {
            LogHelper.monitor("crmOrder已存在");
            return getErrorResult(ErrorCode.Failure.getCode(), "crmOrder已存在");
        }
        ThreeGuaranteesPurDO threeGuaranteesPurDO = new ThreeGuaranteesPurDO();
        ActionResult<String> text = fastGenClient.textGuid();
        if (text.getCode() != ErrorCode.Success.getCode()) {
            return getResult(ErrorCode.IllegalArument, "获取GUID出错");
        }
        String orgId = companyInfoDO.getOrgId();
        String purchaseNo = genDocumentService.genDocumentNo(BillDesc.Purchase, orgId);
        threeGuaranteesPurDO.setId(text.getValue());
        threeGuaranteesPurDO.setPurchaseNo(purchaseNo);
        threeGuaranteesPurDO.setOrgId(orgId);
        //crm传参接收赋值
        String machineNumber = headInfo.getMachineNumber();
        String prodType = headInfo.getProdType();
        String receiverName = headInfo.getReceiverName();
        String receiverPhone = headInfo.getReceiverPhone();
        String sapName = headInfo.getSapName();
        String serviceName = headInfo.getServiceName();
        String serviceNo = headInfo.getServiceNo();
        String servicePhone = headInfo.getServicePhone();
        String serviceSite = headInfo.getServiceSite();
        String receiverAddress = headInfo.getReceiverAddress();
        receiverAddress = StringUtils.isEmpty(receiverAddress) ? "--" : receiverAddress;
        threeGuaranteesPurDO.setCrmOrder(crmOrder);
        threeGuaranteesPurDO.setSettleTypeName("--");
        threeGuaranteesPurDO.setMachineNumber(machineNumber);
        threeGuaranteesPurDO.setProdType(prodType);
        threeGuaranteesPurDO.setReceiverName(receiverName);
        threeGuaranteesPurDO.setReceiverPhone(receiverPhone);
        threeGuaranteesPurDO.setReceiverAddress(receiverAddress);
        threeGuaranteesPurDO.setSapName(sapName);
        threeGuaranteesPurDO.setServiceName(serviceName);
        threeGuaranteesPurDO.setServiceNo(serviceNo);
        threeGuaranteesPurDO.setServicePhone(servicePhone);
        threeGuaranteesPurDO.setServiceSite(serviceSite);

        //===================以下为默认赋值
        threeGuaranteesPurDO.setStatus(2);//默认为已出库状态
        threeGuaranteesPurDO.setGuaraenteesStatus("2");//默认赋值审核通过
        DataDictionaryDO auditDataDictionaryDO=dataDictionaryMapper.itemByCode( GuaraenteesStatus.Name.toString(),threeGuaranteesPurDO.getGuaraenteesStatus());
        if(auditDataDictionaryDO!=null){
            threeGuaranteesPurDO.setStatusDesc(auditDataDictionaryDO.getName());
        }
        threeGuaranteesPurDO.setPrice(BigDecimal.ZERO);//默认赋值价格0
        threeGuaranteesPurDO.setTotalPrice(BigDecimal.ZERO);//默认总价
        threeGuaranteesPurDO.setApplicationDate(new Date());
        //=====================默认赋值结束

        BigDecimal purQty = BigDecimal.ZERO;
        for (ThreeGuaranteesPurJCDetail detail : model.getDetailList()) {
            ThreeGuaranteesPurDetailDO threeGuaranteesPurDetailDO = new ThreeGuaranteesPurDetailDO();
            String materialsDesc = detail.getMaterialsDesc();
            String materialsNo = detail.getMaterialsNo();
            BigDecimal purchaseQty = detail.getPurchaseQty();
            ActionResult<String> textScheduleDetail = fastGenClient.textGuid();
            if (textScheduleDetail.getCode() != ErrorCode.Success.getCode()) {
                throw new Exception("获取GUID出错");
            }
            threeGuaranteesPurDetailDO.setId(textScheduleDetail.getValue());
            threeGuaranteesPurDetailDO.setThreeGuaPurNo(threeGuaranteesPurDO.getId());
            threeGuaranteesPurDetailDO.setMaterialsNo(materialsNo);
            threeGuaranteesPurDetailDO.setMaterialsDesc(materialsDesc);
            threeGuaranteesPurDetailDO.setPurchaseQty(purchaseQty);
            threeGuaranteesPurDetailDO.setDeliveryQty(purchaseQty);
            threeGuaranteesPurDetailDO.setStatus(2);
            threeGuaranteesPurDetailDO.setCreateId("000000");
            threeGuaranteesPurDetailDO.setCreateName("系统同步");
            threeGuaranteesPurDetailDO.setCreateDate(new Date());
            threeGuaranteesPurDetailDO.setPrice(BigDecimal.ZERO);
            threeGuaranteesPurDetailDO.setTotalPrice(threeGuaranteesPurDetailDO.getPrice().multiply(threeGuaranteesPurDetailDO.getPurchaseQty()));
            threeGuaranteesPurDetailDO.setRealQty(purchaseQty);
            threeGuaranteesPurDetailDO.setOutDate(new Date());
            threeGuaranteesPurDetailMapper.add(threeGuaranteesPurDetailDO);
            threeGuaranteesPurDO.setPrice(threeGuaranteesPurDO.getPrice().add(threeGuaranteesPurDetailDO.getPrice()));
            threeGuaranteesPurDO.setTotalPrice(threeGuaranteesPurDO.getTotalPrice().add(threeGuaranteesPurDetailDO.getTotalPrice()));
            purQty = purQty.add(threeGuaranteesPurDetailDO.getPurchaseQty());
        }
        threeGuaranteesPurDO.setPurchaseQty(purQty);
        if (threeGuaranteesPurMapper.add(threeGuaranteesPurDO) > 0) {
            return getResult(ErrorCode.Success, purchaseNo);
        }
        return getResult(ErrorCode.Failure, "插入数据失败");
    }


    /**
     * @Des 随车crm同步三包单到pms
     * @Date 2021/1/19 17:47
     * @Author wangzhaoyu
     * @Param [model]
     * @Return yb.ecp.fast.infra.infra.ActionResult
     */
//    @Transactional
//    public ActionResult synSCThreeGuarantees(ThreeGuaranteesPurAddVO model) throws Exception {
//        if (null == model || null == model.getHeaderInfo() || model.getDetailList().isEmpty()) {
//            return ActionResultUtil.errorActionResult(ErrorCode.IllegalArument);
//        }
//        ThreeGuaranteesPurVO headerInfo = model.getHeaderInfo();
//        String sapCode = headerInfo.getSapCode();
//        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(sapCode);
//        externalParamCheckService.checkParam(fillNeedCheckParan(model));
//        ActionResult<String> result = addThreeGuaranteesPur(model,companyInfoDO);
//        if(!ActionResultUtil.judgeSuccess(result)){
//            throw new Exception(result.getMessage());
//        }
//        //自动创建出库单
//        String purchaseNo = result.getValue();
//        threeGuaranteesOutService.scAutoThreeGuaranteesOut(model,purchaseNo,companyInfoDO);
//
//        return result;
//    }

    private ExternalParamCheckVO fillNeedCheckParan(ThreeGuaranteesPurAddVO model) throws Exception {
        ExternalParamCheckVO param = new  ExternalParamCheckVO();
        if (CollectionUtils.isEmpty(model.getDetailList())) {
            throw new Exception("缺少零件信息");
        }
        List<String> materialsNos = new ArrayList<>();
        for (ThreeGuaranteesPurDetailVO detailVO : model.getDetailList()) {
            materialsNos.add(detailVO.getMaterialsNo());
        }
        param.setMaterialsNos(materialsNos);
        param.setSapCode(model.getHeaderInfo().getSapCode());
        param.setDeliveryTypeId(model.getHeaderInfo().getDeliveryTypeId());
        param.setSettleTypeId(model.getHeaderInfo().getSettleTypeId());
        return param;
    }
}
